<template>
  <div v-loading.fullscreen.lock="loading"
       :element-loading-text="$t('loading')"
       :class="['aui-wrapper', { 'aui-sidebar--fold': $store.state.sidebarFold }]">
    <template>
      <main-navbar :message="headerMenuName"
                   @setheaderMenuName="setheaderMenuName" />
      <main-sidebar v-if="headerMenuName != '主页'" />
      <!-- <div class="aui-content__wrapper"> -->
      <div v-if="headerMenuName != '主页'"
           :class="headerMenuName != '主页' ? 'aui-content__wrapper':'' ">
        <main-content v-if="!$store.state.contentIsNeedRefresh" />
      </div>
      <div v-else
           class="aui-content__wrapper"
           style="margin-left: 0;">
        <template>
          <keep-alive v-if="getRouterView">
            <router-view />
          </keep-alive>
          <router-view v-else />
        </template>
      </div>
    </template>
  </div>
</template>

<script>
import mixinViewModule from '@/mixins/view-module'
import MainNavbar from './main-navbar'
import MainSidebar from './main-sidebar'
import MainContent from './main-content'
import debounce from 'lodash/debounce'
import { clearLoginInfo } from '@/utils'
import CryptoTool from '@/utils/cryptoTool'
import { mapMutations } from 'vuex'
export default {
  mixins: [mixinViewModule],
  provide () {
    return {
      // 刷新
      refresh () {
        this.$store.commit('setContentIsNeedRefresh', true)
        this.$nextTick(() => {
          this.$store.commit('setContentIsNeedRefresh', false)
        })
      }
    }
  },
  data () {
    return {
      mixinViewModuleOptions: {
        // getReportTemplateURL: '/tb/accessory/getReportTemplate', // 获取所有模板
        // getStatusURL: '/tb/takeEffectRule/getStatus'
        // getBySurfaceNameURL: '/tb/globalSign/getBySurfaceName'
      },
      loading: true,
      visible: false,
      visiblePass: false,
      titleVisible: true,
      time: Date.now(),
      dataForm: {
        userType: 2,
        username: ''
      },
      getRouterView: null,
      headerMenuName: ''
    }
  },
  computed: {
    isShow () {
      return this.$store.state.user.superAdmin === 1
    }
  },
  components: {
    MainNavbar,
    MainSidebar,
    MainContent
  },
  watch: {
    $route (to, from) {
      if (to.name === 'home') {
        this.getRouterView = false
      } else if (to.name === undefined) {
        this.getRouterView = false
      } else {
        this.getRouterView = true
      }
      this.routeHandle(this.$route)
    }
    // $route: 'routeHandle'
  },
  created () {
    this.getUserInfo()
    this.getIndexRouter()
    this.setRefresheChar(false)
    this.getI18nList()
    this.windowResizeHandle()
    this.routeHandle(this.$route)
    window.requestAnimationFrame(this.nowTimes)
    this.visiblePass = false
    this.titleVisible = true
    this.visible = false
    // this.getReportTemplate()
    let mode = localStorage.getItem('mode') || 'light'
    // this.getBySurfaceName('WorkFlow')
    // this.getBySurfaceName('WriteWorkFlow')
    // this.getStatus()
    this.setTheme(mode)
    Promise.all([
      this.getPermissions(),
      this.nowTimes()
    ]).then(() => {
      this.loading = false
      this.$store.state.contentTabs = this.$store.state.contentTabs.filter(item => item.name === 'home')
      this.$router.push({ name: 'home' })
    })
  },
  methods: {
    ...mapMutations(['setTheme', 'setRefresheChar', 'setConsole', 'setWorkflowStatus', 'setRulesStatus', 'setFillingflowStatus', 'setQuestionTemplate']),
    // getReportTemplate () {
    //   this.getData({ url: this.mixinViewModuleOptions.getReportTemplateURL }).then(res => {
    //     if (res.code !== 0) {
    //       return false
    //     }
    //     this.setQuestionTemplate(res.data[0])
    //     res.data.map(item => {
    //       if (item.status) {
    //         this.setQuestionTemplate(item)
    //       }
    //     })
    //   })
    // },
    // 获取工作流状态
    // getBySurfaceName (name) {
    //   this.getData({
    //     url: this.mixinViewModuleOptions.getBySurfaceNameURL,
    //     paramData: {
    //       surfaceName: name
    //     }
    //   }).then(res => {
    //     if (res.code !== 0) {
    //       return false
    //     }
    //     if (name === 'WriteWorkFlow') {
    //       this.setFillingflowStatus(res.data.sign)
    //     } else {
    //       this.setWorkflowStatus(res.data.sign)
    //     }
    //   })
    // },
    // 获取规则状态
    // getStatus () {
    //   this.getData({ url: this.mixinViewModuleOptions.getStatusURL }).then(res => {
    //     if (res.code !== 0) {
    //       return
    //     }
    //     this.setRulesStatus(res.data.sign)
    //   })
    // },
    setheaderMenuName (val) {
      this.headerMenuName = val
      // console.log(this.headerMenuName)
    },
    // 获取动态的国际化语言列表
    getI18nList () {
      this.$http.get('/system/sysVue/getI18n').then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        let i18nObj = {}
        res.data.i18nTile.map(item => {
          i18nObj[item] = {}
        })
        res.data.i18n.map(item => {
          i18nObj[item.label] = item.value
        })
        // 动态加载语言包
        this.$i18n.mergeLocaleMessage('zh-CN', i18nObj)
      })
    },
    /**
     * 时间格式转换
     */
    timeFormate (timeStamp) {
      let year = new Date(timeStamp).getFullYear()
      let month = new Date(timeStamp).getMonth() + 1 < 10 ? '0' + (new Date(timeStamp).getMonth() + 1) : new Date(timeStamp).getMonth() + 1
      let date = new Date(timeStamp).getDate() < 10 ? '0' + new Date(timeStamp).getDate() : new Date(timeStamp).getDate()
      let hh = new Date(timeStamp).getHours() < 10 ? '0' + new Date(timeStamp).getHours() : new Date(timeStamp).getHours()
      let mm = new Date(timeStamp).getMinutes() < 10 ? '0' + new Date(timeStamp).getMinutes() : new Date(timeStamp).getMinutes()
      this.time = year + '年' + month + '月' + date + '日' + ' ' + hh + ':' + mm
    },
    /**
     * 当前时间
     * 并转换时间格式
     */
    nowTimes () {
      this.timeFormate(new Date())
      window.requestAnimationFrame(this.nowTimes)
    },
    /**
     * 窗口改变大小
     */
    windowResizeHandle () {
      this.$store.state.sidebarFold = document.documentElement['clientWidth'] <= 992 || false
      window.addEventListener('resize', debounce(() => {
        this.$store.state.sidebarFold = document.documentElement['clientWidth'] <= 992 || false
      }, 150))
    },
    /**
     * 路由, 监听
     */
    routeHandle (route) {
      if (!route.meta.isTab) {
        return false
      }
      var tab = this.$store.state.contentTabs.filter(item => item.name === route.name)[0]
      if (!tab) {
        tab = {
          ...window.SITE_CONFIG['contentTabDefault'],
          ...route.meta,
          'name': route.name,
          'params': { ...route.params },
          'query': { ...route.query }
        }
        this.$store.state.contentTabs = this.$store.state.contentTabs.concat(tab)
      }
      this.$store.state.sidebarMenuActiveName = tab.menuId
      this.$store.state.contentTabsActiveName = tab.name
    },
    /**
     * 获取当前用户信息
     */
    async getUserInfo () {
      await this.$nextTick(() => {
        this.$http.get('/getUserInfo').then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.$store.state.user.id = res.data.id
          this.$store.state.user.name = res.data.username
          this.$store.state.user.deptId = res.data.deptId
          this.$store.state.user.superAdmin = res.data.superAdmin
          this.$store.state.user.realName = res.data.realName
          this.$store.state.user.deptName = res.data.deptName
          this.$store.state.user.phone = res.data.phone
          this.$store.state.user.showPage = res.data.showPage
          this.$store.state.user.userType = res.data.userType
        }).catch(() => {
        })
      })
    },
    // 获取默认主页路由
    async getIndexRouter () {
      await this.$nextTick(() => {
        this.$http.get('/system/sysGlobalConfig/getSysGlobalConfig?type=3').then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          // 默认主页路由放入store中
          this.$store.state.user.router = res.data.value
        }).catch(() => {
        })
      })
    },
    /**
     * 获取权限
     */
    getPermissions () {
      return this.$http.get('/system/sysPermission/permissions?usePort=0').then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        const permissions = CryptoTool.encrypt(res.data.join(','))
        localStorage.setItem('permissions', permissions)
        window.SITE_CONFIG['storeState'].permissions = res.data
        // 判断是否显示大屏控制台
        const bool = this.$hasPermission('master:console') || this.$hasPermission('vehicle:monitoring') || this.$hasPermission('site:monitoring')
        this.setConsole(bool)
      }).catch(() => { })
    },
    /**
     * 退出
     */
    logoutHandle () {
      this.$confirm(this.$t('prompt.info', { 'handle': this.$t('logout') }), this.$t('prompt.title'), {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        type: 'warning'
      }).then(() => {
        this.$http.put('/logout').then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          clearLoginInfo()
          window.location.reload()
        }).catch(() => { })
      }).catch(() => { })
    }
  }
}
</script>

<style lang="scss">
</style>
